package cn.itcast.realm;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class SaasRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private ModuleService moduleService;

//    认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("++++++++++++++认证方法++++++++++++++");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String email = token.getUsername();
        String password_page = new String(token.getPassword());
        User user = userService.findByEmail(email);
//            判断根据邮箱是否能查询到用户
        if(user==null){ //如果没有查询到 邮箱错误
            return null ; // 如果return null那么 subject,login(token)方法那里就会抛异常
        }else{ //如果有，比较密码（password加盐后再和表中的密码做比较）
            String password_db = user.getPassword();
            if(!password_page.equals(password_db)){ // 比较不一致，密码输错
               return  null;
            }
//            Object principal 主角, Object credentials 加密后的密码, String realmName 当前类名
            return new SimpleAuthenticationInfo(user,password_db,getName());
        }
    }

//    授权    通过这个方法告诉shiro框架当前登录人有哪些权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("**************授权方法**************");
        //        获取当前登录人
       /* Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();*/
        User user = (User) principalCollection.getPrimaryPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        查询当前登录人有哪些权限
        List<Module> moduleList = moduleService.findModuleListByUser(user);
        for (Module module : moduleList) {
            info.addStringPermission(module.getName());
        }
        info.addRole("SVIP");

        return info;
    }


}
